/**
   Copyright 2014 Фроловский А. В.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   This file is a part of MyStats project
 */

package foo.mystats.contentprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import foo.mystats.db.DataTable;
import foo.mystats.db.DbOpenHelper;
import foo.mystats.db.RowTable;

public class DataContentProvider extends ContentProvider {
  private DbOpenHelper dbOpenHelper;

  private static final int DATA = 30;
  private static final int DATA_ID = 40;

  private static final String AUTHORITY = "foo.mystats.contentprovider.DataContentProvider";

  private static final String BASE_PATH = "data";
  public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);

  private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);

  static {
    sURIMatcher.addURI(AUTHORITY, BASE_PATH, DATA);
    sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", DATA_ID);
  }

  @Override
  public boolean onCreate() {
    dbOpenHelper = new DbOpenHelper(getContext());
    return false;
  }

  @Override
  public Cursor query(Uri uri, String[] projection, String selection,
      String[] selectionArgs, String sortOrder) {

    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    queryBuilder.setTables(String.format("%1$s LEFT JOIN %2$s ON %1$s.%3$s = %2$s.%4$s",
        DataTable.TABLE_DATA,
        RowTable.TABLE_ROW,
        DataTable.COLUMN_ROW_ID,
        RowTable.COLUMN_ID));

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case DATA:
        break;
      case DATA_ID:
        queryBuilder.appendWhere(DataTable.TABLE_DATA + "." + DataTable.COLUMN_ID + "=" + uri.getLastPathSegment());
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }

    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
  }

  @Override
  public String getType(Uri uri) {
    return null;
  }

  @Override
  public Uri insert(Uri uri, ContentValues values) {
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    long id = 0;

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case DATA:
        id = db.insert(DataTable.TABLE_DATA, null, values);
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return Uri.parse(BASE_PATH + "/" + id);
  }

  @Override
  public int delete(Uri uri, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    int datasDeleted = 0;

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case DATA:
        datasDeleted = db.delete(DataTable.TABLE_DATA, selection, selectionArgs);
        break;
      case DATA_ID:
        String id = uri.getLastPathSegment();
        if (TextUtils.isEmpty(selection)) {
          datasDeleted = db.delete(DataTable.TABLE_DATA,
              DataTable.COLUMN_ID + "=" + id,
              null);
        } else {
          datasDeleted = db.delete(DataTable.TABLE_DATA,
              DataTable.COLUMN_ID + "=" + id + " and " + selection,
              selectionArgs);
        }
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return datasDeleted;
  }

  @Override
  public int update(Uri uri, ContentValues values, String selection,
      String[] selectionArgs) {

    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    int rowsUpdated = 0;

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case DATA:
        rowsUpdated = db.update(DataTable.TABLE_DATA, values, selection, selectionArgs);
        break;
      case DATA_ID:
        String id = uri.getLastPathSegment();
        if (TextUtils.isEmpty(selection)) {
          rowsUpdated = db.update(DataTable.TABLE_DATA,
              values,
              DataTable.COLUMN_ID + "=" + id,
              null);
        } else {
          rowsUpdated = db.update(DataTable.TABLE_DATA,
              values,
              DataTable.COLUMN_ID + "=" + id + " and " + selection,
              selectionArgs);
        }
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return rowsUpdated;
  }
}
